package baseFx.springboot.components;

import baseFx.log.FxLog;
import baseFx.log.FxLogSetting;
import baseFx.log.Level;
import baseFx.springboot.FxController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RequestMapping("fx/log")
public class FxLogController extends FxController {
    @GetMapping("getAll")
    public Object getAll() {
        List<GetAllVo> rs = new ArrayList<>();
        List<String> names = FxLog.getNames();
        for (String name : names) {
            GetAllVo vo = new GetAllVo();
            vo.name = name;
            FxLogSetting fs = FxLog.getFileSetting(vo.name);
            FxLogSetting cs = FxLog.getConsoleSetting(vo.name);
            if (fs == null && cs == null) {
                continue;
            }
            for (Level lv : fs.getLevels()) {
                vo.file_lv.add(lv.name());
            }
            vo.file_pos.addAll(fs.getLocation());
            for (Level lv : cs.getLevels()) {
                vo.cons_lv.add(lv.name());
            }
            vo.cons_pos.addAll(cs.getLocation());
            rs.add(vo);
        }
        return rs;
    }

    @PostMapping("set")
    public String setLog() {
        String name = getStringParam("name").get();
        String fileLv = getStringParam("file_lv").orElse("");
        String filePos = getStringParam("file_pos").orElse("");
        String consLv = getStringParam("cons_lv").orElse("");
        String consPos = getStringParam("cons_pos").orElse("");
        if (FxLog.isFxLog(name) == false) {
            return "不是FxLog";
        }
        FxLogSetting fs = FxLog.getFileSetting(name);
        fs.getLevels().clear();
        fs.getLocation().clear();
        for (String item : fileLv.split(",")) {
            fs.getLevels().add(Level.valueOf(item));
        }
        if (filePos.length() > 0) {
            fs.getLocation().addAll(Arrays.asList(filePos.split(",")));
        }

        FxLogSetting cs = FxLog.getConsoleSetting(name);
        cs.getLevels().clear();
        cs.getLocation().clear();
        for (String item : consLv.split(",")) {
            cs.getLevels().add(Level.valueOf(item));
        }
        if (consPos.length() > 0) {
            cs.getLocation().addAll(Arrays.asList(consPos.split(",")));
        }
        return "ok";
    }

    public static class GetAllVo {
        public String name = "";
        public List<String> file_lv = new ArrayList<>();
        public List<String> file_pos = new ArrayList<>();
        public List<String> cons_lv = new ArrayList<>();
        public List<String> cons_pos = new ArrayList<>();
    }
}
